package com.adam.zk.controller;

import com.adam.zk.controller.request.NewFoodRequest;
import com.adam.zk.model.Food;
import com.adam.zk.service.FoodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/food")
@Slf4j
public class FoodController {

    @Autowired
    private FoodService foodService;

    @PostMapping(path = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public Food addFoodWithoutBindingResult(@Valid NewFoodRequest newFood) {
        return foodService.saveFood(newFood.getName(), newFood.getPrice());
    }

    @PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public Food addJsonFoodWithoutBindingResult(@Valid @RequestBody NewFoodRequest newFood) {
        return foodService.saveFood(newFood.getName(), newFood.getPrice());
    }

    @GetMapping(path = "/", params = "!name")
    public List<Food> getAll() {
        return foodService.getAllFood();
    }

    @GetMapping("/{id}")
    public Food getById(@PathVariable Long id) {
        Food food = foodService.getFood(id);
        log.info("Food {}:", food);
        return food;
    }

    @GetMapping(path = "/", params = "name")
    public Food getByName(@RequestParam String name) {
        return foodService.getFood(name);
    }
}
